package com.suxin.thread.future;

import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.FutureTask;

/**
 * @author Tang
 * @classname ListenableFutureTask
 * @description [ 扩展 FutureTask 增加执行完成后回调的能力 ]
 * @date 2023/2/7 09:51
 */
public abstract class ListenableFutureTask<V> extends FutureTask<V> implements ListenableFuture<V>{

    private final ListenableFutureTaskCallbackRegister<V> callbacks = new ListenableFutureTaskCallbackRegister<>();

    public ListenableFutureTask(Callable<V> callable) {
        super(callable);
    }

    public ListenableFutureTask(Runnable runnable, V result) {
        super(runnable, result);
    }

    @Override
    public void addCallback(ListenableFutureCallback<V> callback) {
        callbacks.addCallback(callback);
    }

    @Override
    public void addCallback(SuccessCallback<V> successCallback, FailureCallback failureCallback) {
        callbacks.addSuccessCallback(successCallback);
        callbacks.addFailureCallback(failureCallback);
    }

    @Override
    public CompletableFuture<V> completable() {
        CompletableFuture<V> completableFuture = new CompletableFuture<>();
        callbacks.addSuccessCallback(completableFuture::complete);
        callbacks.addFailureCallback(completableFuture::completeExceptionally);
        return completableFuture;
    }

    @Override
    protected void done() {
        super.done();
        try {
            V v = get();
            callbacks.success(v);
        } catch (Exception e) {
            callbacks.failure(e);
        }
    }

}
